from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.responses import JSONResponse
from qcloud_cos import CosS3Client

from src.models import FillRequest
from src.dependencies.cos_client import get_cos_client
from src.core.excel_processor import process_excel_filling

router = APIRouter()

@router.post("/fill-template",
             summary="Fill data into a specified built-in Excel .xlsx template using a JSON request body",
             response_description="Filled .xlsx file download URLs")
async def fill_excel_template(
    fill_data: FillRequest = Body(..., description="JSON payload containing template name and sheet-specific fill instructions."),
    cos_client: CosS3Client = Depends(get_cos_client)
):
    """
    Fills data into a pre-defined Excel .xlsx template whose name is provided in the request body.
    The request body expects a JSON object with `template_name` and `sheet_instructions`.

    **Example Request Body:**
    ```json
    {
        "template_name": "通用销售报表.xlsx",
        "sheet_instructions": {
            "销售数据": [
                {
                    "type": "placeholder",
                    "data": {
                        "report_name": "Q3销售报告",
                        "report_date": "2023-10-27",
                        "product_1": "产品A", "sales_1": 100, "price_1": 10.5, "total_1": 1050.0,
                        "product_2": "产品B", "sales_2": 200, "price_2": 5.0, "total_2": 1000.0,
                        "product_3": "产品C", "sales_3": 50, "price_3": 20.0, "total_3": 1000.0,
                        "grand_total": 3050.0
                    }
                },
                {
                    "type": "cell",
                    "data": {
                        "A1": "季度销售总览"
                    }
                }
            ],
            "摘要": [
                {
                    "type": "placeholder",
                    "data": {
                        "manager_name": "张三",
                        "department": "市场部"
                    }
                },
                {
                    "type": "cell",
                    "data": {
                        "A1": "摘要信息"
                    }
                }
            ]
        }
    }
    ```
    """
    result = await process_excel_filling(fill_data, cos_client)
    return JSONResponse(status_code=200, content=result) 